<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Webinar {

        function __construct()
        {
        }

        public function verify($binars = array(), $URL, $SALT)
        {
                $CI = &get_instance();
                $i = 0;
                foreach($binars as $row)
                {
                        $info = $CI->bbb->getMeetingInfoArray($row['ID'],
                                sha1($row['ID'].$row['UID'].'webinar'),
                                $URL, $SALT);
                        if(isset($info['returncode']))
                        {
                                $CI->wdb->end($row['ID']);
                                unset($binars[$i]);
                        }
                        else $binars[$i]['participantCount'] = $info['participantCount'];
                        $i++;
                }
                return $binars;
        }

        public function now_running($URL, $SALT)
        {
                $CI = &get_instance();
		$UID = @$CI->uid;
                $binars = $CI->wdb->nowRunning();
                $binars = $this->verify($binars, $URL, $SALT);
                $data = array();
		$dt['base_url'] = base_url();
                $i = 0;
                foreach($binars as $row)
                {
			$data[$i] = $row;
                        if($UID == $row['UID'] || $CI->role == 'admin')
                        {
				$dt['id'] = $row['ID'];
				($CI->role == 'admin')? $dt['adm'] = '/1': $dt['adm'] = '';
                                $data[$i] += array(
                                    'join_link' => $CI->parser->parse('templates/join_link.html', $dt, true),
                                    'end_link' => $CI->parser->parse('templates/end_link.html', $dt, true),);
				$data[$i]['status'] = 'Вы - лектор.';
				$data[$i] += array('join_status' => '');
                        }
			else if($data[$i]['status'] == 1)
			{
				$data[$i]['status'] = 'Закрытый вебинар.';
				if($data[$i]['count'] <= $data[$i]['participantCount'])
				{
					$data[$i] += array('join_link' => '');
					$data[$i] += array('end_link' => '');
					$data[$i] += array('join_status' => 'Вход недоступен (нет мест)');
				}
				else if($UID > 0  && $this->privileges($row['PID']) == 1)
				{
					$dt['id'] = $row['ID'];
					$data[$i] += array('join_link' => $CI->parser->parse('templates/join_link.html', $dt, true));
					$data[$i] += array('join_status' => '');
				}
				else
				{
                                        $data[$i] += array('join_link' => '');
					$data[$i] += array('join_status' => 'Вход недоступен (у вас нет прав).');
				}
				$data[$i] += array('end_link' => '');
			}
                        else if($data[$i]['count'] > $data[$i]['participantCount'])
                        {
				$dt['id'] = $row['ID'];
                                if($UID > 0)
                                        $data[$i] += array('join_link' => $CI->parser->parse('templates/join_link.html', $dt, true));
                                else
                                        $data[$i] += array('join_link' => '');
                                $data[$i] += array('end_link' => '');
				$data[$i]['status'] = 'Открытый вебинар.';
				$data[$i] += array('join_status' => '');
                        }
			else
			{
                                $data[$i] += array('join_link' => '');
                                $data[$i] += array('end_link' => '');
				$data[$i]['status'] = 'Открытый вебинар.';
				$data[$i] += array('join_status' => 'Вход недоступен (нет мест)');
			}
                        $i++;
                }
                return $data;
        }
	
	public function kill($id, $uid)
	{
		$CI = &get_instance();
		if($CI->wdb->is_running($id))
                {
			//$CI->load->library('BigBlueButton', null, 'bbb');
			$salt = @$CI->salt;
			$url = @$CI->bbb_url;
			$pw = sha1($id.$uid.'webinar');
			$CI->wdb->end($id);
			$res = $CI->bbb->endMeeting($id, $pw, $url, $salt);
                }
	}
	
	public function del($id)
	{
		$CI = &get_instance();
		$CI->wdb->delete($id);
	}
	
	public function run($pid)
	{
		$CI = &get_instance();
		$uid = $CI->wdb->getPlUID($pid);
		$user = $CI->check->getUserByID($uid);
		$username = $user[0]['surname'];//." ".
                        /*substr($user[0]['firstname'], 0, 2).".".
                        substr($user[0]['secondname'], 0, 2).".";*/
		$meetingID = $CI->wdb->create($uid, $pid);
		$data = $CI->wdb->plannedData($pid);
		$welcome = 'Добро пожаловать!'."\n".'Тема: "'.$data['subj'].'".';
		$mPW = sha1($meetingID.$uid.'webinar');
		$aPW = sha1($meetingID.'attendee');
		$count =  @$data['count'];
		$SALT = @$CI->salt;
		$URL = @$CI->bbb_url;
		$logoutURL = base_url().'control/end/'.$meetingID;
		$res = $CI->bbb->createMeetingArray($username,
			$meetingID, $welcome, $mPW, $aPW, $SALT, $URL, $logoutURL);
	}
	
	function mail($to, $subj, $msg, $reply = '')
        {
                //$this->seq();
                if(!(isset($to) || isset($subj) || isset($msg))) return false;
		
		$CI = @get_instance();
                $CI->load->library('email');
                $config['protocol'] = 'smtp';
                $config['charset'] = 'utf-8';
                $config['wordwrap'] = TRUE;
                $config['smtp_host'] = 'smtp.vvsu.ru';
                $config['smtp_user'] = 'e-class';
                $config['smtp_pass'] = 'su9w3b';
                $config['send_multipart'] = FALSE;
                $config['smtp_timeout'] = 5;
                $config['crlf'] = "\r\n";
                $config['newline'] = "\r\n";
                $config['validate'] = TRUE;
                $CI->email->initialize($config);

                $CI->email->from('e-class@vvsu.ru', 'Webinar VVSU');
                $CI->email->reply_to($reply);//, mb_convert_encoding('Модератор', 'cp1251'));
                $CI->email->to($to);
                $CI->email->subject(mb_convert_encoding($subj, 'UTF-8'));
                $CI->email->message($msg);
		
		//log_message('debug', $this->email->print_debugger());
                
		if(!$CI->email->send()) return false;
                return true;

        }

	function privileges($id)
	{
		$CI = &get_instance();
		$CHK = $CI->check->checkObjRights($id, $CI->uid);
		return $CHK;
	}
	
	function isInMeeting($id, $uname, $mPW, $URL, $SALT)
	{
		$CI = &get_instance();
		$UID = @$CI->uid;
		$meeting = $CI->bbb->getMeetingInfoArray($id, $mPW, $URL, $SALT);
		foreach($meeting['attendees'] as $key => $val)
			if($val->attendee->fullName == $uname) return true;
		return false;
	}
}
